import { defineStore } from 'pinia';
import { ref } from 'vue';

export interface Member {
  id: string;
  name: string;
  phone: string;
  email?: string;
  avatar?: string;
  status: 'active' | 'inactive';
  joinDate: string;
  notes?: string;
  createdAt: string;
  updatedAt: string;
}

export interface FilterOptions {
  status?: 'active' | 'inactive' | 'all';
  sortBy?: 'name' | 'joinDate' | 'createdAt';
  sortOrder?: 'asc' | 'desc';
}

export const useMemberStore = defineStore('member', () => {
  const memberList = ref<Member[]>([]);
  const currentMember = ref<Member | null>(null);
  const searchKeyword = ref<string>('');
  const filterOptions = ref<FilterOptions>({
    status: 'all',
    sortBy: 'createdAt',
    sortOrder: 'desc',
  });
  const loading = ref<boolean>(false);
  const pagination = ref({
    current: 1,
    pageSize: 10,
    total: 0,
  });

  const setMemberList = (members: Member[]) => {
    memberList.value = members;
  };

  const addMember = (member: Member) => {
    memberList.value.unshift(member);
  };

  const updateMember = (updatedMember: Member) => {
    const index = memberList.value.findIndex(m => m.id === updatedMember.id);
    if (index !== -1) {
      memberList.value[index] = updatedMember;
    }
  };

  const deleteMember = (memberId: string) => {
    const index = memberList.value.findIndex(m => m.id === memberId);
    if (index !== -1) {
      memberList.value.splice(index, 1);
    }
  };

  const setCurrentMember = (member: Member | null) => {
    currentMember.value = member;
  };

  const setSearchKeyword = (keyword: string) => {
    searchKeyword.value = keyword;
  };

  const setFilterOptions = (options: Partial<FilterOptions>) => {
    filterOptions.value = { ...filterOptions.value, ...options };
  };

  const setLoading = (isLoading: boolean) => {
    loading.value = isLoading;
  };

  const setPagination = (page: number, pageSize: number, total: number) => {
    pagination.value = { current: page, pageSize, total };
  };

  return {
    memberList,
    currentMember,
    searchKeyword,
    filterOptions,
    loading,
    pagination,
    setMemberList,
    addMember,
    updateMember,
    deleteMember,
    setCurrentMember,
    setSearchKeyword,
    setFilterOptions,
    setLoading,
    setPagination,
  };
});